package com.gant;

import com.gant.controller.JsonController;
import com.gant.view.MainView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.input.MouseButton;
import javafx.stage.Stage;

import java.util.Objects;

public class JSONViewerApp extends Application {
    private MainView mainView;
    private JsonController controller;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        mainView = new MainView();
        controller = new JsonController(mainView);// 注入MainView实例

        // 绑定事件
        mainView.getOpenButton().setOnAction(e ->
                controller.handleOpenFile(primaryStage)
        );

        mainView.getSearchButton().setOnAction(e ->
                controller.handleSearch()
        );

        // 分页按钮事件示例
        mainView.getNextPageButton().setOnAction(e -> {
            if (controller.getCurrentPage() < controller.getTotalPages()) {
                controller.setCurrentPage(controller.getCurrentPage() + 1);
                controller.loadPage(controller.getCurrentPage());
                controller.updatePagination();
            }
        });
        // //双击事件
        mainView.getJsonTreeView().setOnMouseClicked(event -> {
            if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) {

                TreeItem<String> selectedItem = mainView.getJsonTreeView().getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    controller.getNavigationStack().push(controller.getCurrentRootItem());
                    controller.setCurrentRootItem(selectedItem);
                    controller.setCurrentPage(1);
                    controller.updatePagination();
                    controller.loadPage(controller.getCurrentPage());
                }
            }
        });

        mainView.getBackButton().setOnAction(e ->
                controller.navigateBack()
        );

        // 场景设置
        Scene scene = new Scene(mainView.getRoot(), 1000, 600);
        scene.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/gant/styles.css")).toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setTitle("JSON Viewer");
        primaryStage.show();
    }
}